package net.lab1024.sa.admin.module.basedata.customer.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import net.lab1024.sa.admin.module.basedata.customer.domain.entity.CustomerContact;
import net.lab1024.sa.admin.module.basedata.customer.mapper.CustomerContactMapper;
import net.lab1024.sa.base.common.exception.BusinessException;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class CustomerContactServiceImpl {

    @Autowired
    private CustomerContactMapper customerContactMapper;


    /**
     * 根据客户编码查询联系人信息
     *
     * @param customerCode
     * @return
     */
    public List<CustomerContact> getCustomerContactByCustomerCode(String customerCode) {
        if (customerCode == null) {
            throw new BusinessException("查询客户联系人信息,客户编号不能为空");
        }
        LambdaQueryWrapper<CustomerContact> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerContact::getCustomerCode, customerCode);
        return customerContactMapper.selectList(wrapper);
    }

    
    public void saveOrUpdateCustomerContact(List<CustomerContact> customerContactList) {
        if (CollectionUtils.isEmpty(customerContactList)) {
            throw new BusinessException("客户联系人信息不能为空");
        }

        if (customerContactList.get(0).getCustomerCode() == null) {
            throw new BusinessException("客户编号不能为空");
        }
        List<CustomerContact> customerContactOld = getCustomerContactByCustomerCode(customerContactList.get(0).getCustomerCode());

        if (CollectionUtils.isNotEmpty(customerContactOld)) {
            //    删除所有数据
            customerContactMapper.deleteByCustomerCode(customerContactList.get(0).getCustomerCode());
        }
        // 新增客户联系人
        for (CustomerContact customerContact : customerContactList) {
            customerContact.setCustomerCode(customerContactList.get(0).getCustomerCode());
            customerContact.setVersion(customerContact.getVersion() + 1);
            //    新增
            customerContactMapper.insert(customerContactList);
        }

    }
}
